// api/src/utils/recommendationClient.js
import fetch from "node-fetch";
import config from "../../config";

// 获取推荐服务URL
const RECOMMENDER_URL =
  process.env.RECOMMENDER_URL || "http://localhost:8080/api/v1";

/**
 * 获取个性化推荐
 * @param {string} userId - 用户ID
 * @param {number} count - 推荐数量
 * @returns {Promise<Object>} - 推荐结果
 */
export const getPersonalizedRecommendations = async (userId, count = 10) => {
  try {
    const response = await fetch(
      `${RECOMMENDER_URL}/recommendations?userId=${userId}&count=${count}`
    );
    console.log("获取个性化推荐:", response);

    if (!response.ok) {
      throw new Error(`推荐服务错误: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("获取推荐失败:", error);
    return { recommendations: [] };
  }
};

/**
 * 获取相似资源推荐
 * @param {string} torrentId - 种子ID
 * @param {string} userId - 用户ID (可选)
 * @param {number} count - 推荐数量
 * @returns {Promise<Object>} - 推荐结果
 */
export const getSimilarRecommendations = async (
  torrentId,
  userId = null,
  count = 6
) => {
  try {
    let url = `${RECOMMENDER_URL}/recommendations/similar?torrentId=${torrentId}&count=${count}`;
    if (userId) url += `&userId=${userId}`;

    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`推荐服务错误: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("获取相似资源推荐失败:", error);
    return { recommendations: [] };
  }
};

/**
 * 保存用户偏好设置
 * @param {string} userId - 用户ID
 * @param {Object} preferences - 用户偏好
 * @returns {Promise<Object>} - 操作结果
 */
// 保存用户偏好的函数
export async function saveUserPreferences(userId, preferences) {
  try {
    const response = await fetch(`${RECOMMENDER_URL}/user-preferences`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        userId,
        explicitPreferences: preferences, // 注意这里修改了字段名
      }),
    });

    if (!response.ok) {
      throw new Error(`服务器返回错误: ${response.status}`);
    }

    // 检查是否有内容返回
    const text = await response.text();
    if (!text || text.trim() === "") {
      console.log("服务器返回空响应，但请求成功");
      return { success: true };
    }

    // 尝试解析JSON
    try {
      return JSON.parse(text);
    } catch (e) {
      console.log("响应不是JSON格式，但请求成功");
      return { success: true };
    }
  } catch (error) {
    console.error("保存用户偏好失败:", error);
    throw error;
  }
}
/**
 * 记录用户行为
 * @param {Object} behavior - 用户行为数据
 * @returns {Promise<void>}
 */
export const recordUserBehavior = async (behavior) => {
  try {
    const response = await fetch(`${RECOMMENDER_URL}/user-behaviors`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(behavior),
    });

    if (!response.ok) {
      throw new Error(`推荐服务错误: ${response.status}`);
    }
  } catch (error) {
    console.error("记录用户行为失败:", error);
    // 静默失败，不影响用户体验
  }
};

export default {
  getPersonalizedRecommendations,
  getSimilarRecommendations,
  saveUserPreferences,
  recordUserBehavior,
};
